package data

import (
	"context"
	"github.com/go-kratos/kratos/contrib/registry/consul/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/middleware/validate"
	"github.com/go-kratos/kratos/v2/registry"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/google/wire"
	"github.com/hashicorp/consul/api"
	v1 "review-b/api/review/v1"
	"review-b/internal/conf"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewRegistryClient, NewReviewServiceClient, NewData, NewBusinessRepo)

// Data .
type Data struct {
	// TODO wrapped database client
	//嵌入一个grpc client，通过这个client去调用review-service服务
	rc v1.ReviewClient
}

// NewData .
func NewData(c *conf.Data, rc v1.ReviewClient, logger log.Logger) (*Data, func(), error) {
	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	return &Data{
		rc: rc,
	}, cleanup, nil
}

// 服务发现的构造函数
func NewRegistryClient(c *conf.Registry) registry.Discovery {
	c1 := api.DefaultConfig()

	c1.Address = c.Consul.Address
	c1.Scheme = c.Consul.Scheme
	client, err := api.NewClient(c1)
	if err != nil {
		panic(err)
	}
	// new reg with consul client
	reg := consul.New(client)
	return reg
}

func NewReviewServiceClient(d registry.Discovery) v1.ReviewClient {
	conn, err := grpc.DialInsecure(context.Background(),
		grpc.WithEndpoint("discovery:review-service"),
		grpc.WithDiscovery(d),
		grpc.WithEndpoint("127.0.0.1:9000"),
		grpc.WithMiddleware(
			recovery.Recovery(),
			validate.Validator(),
		),
	)
	if err != nil {
		panic(err)
	}
	return v1.NewReviewClient(conn)
}
